#include"Log.h"
#include<time.h>
#include<sstream>
#include<stdlib.h>
#include<sys/socket.h>
#include<iostream>
#include<sys/types.h>
#include<arpa/inet.h>
#include<unistd.h>

std::atomic_flag Log::lock_log = ATOMIC_FLAG_INIT;
std::ofstream Log::l("my-web.log");

void Log::log(int fd, const std::string &sl, const std::string &s, const std::string &length){
  std::ostringstream logger;
  struct sockaddr_in peeraddr;
  char ip[INET_ADDRSTRLEN];
  socklen_t peerlen;
  getpeername(fd, (struct sockaddr *)&peeraddr, &peerlen);
  inet_ntop(AF_INET, &peeraddr.sin_addr, ip, sizeof(ip));
  logger << ip << " - - ";
  time_t rawtime;
  struct tm *timeinfo;
  char buf[80];
  time(&rawtime);
  timeinfo = localtime (&rawtime);
  strftime (buf,80,"[%d/%b/%Y:%X -0400]",timeinfo);
  logger << buf << " " << "\"" << sl << "\"" << " " << s << " " << length;
  while(lock_log.test_and_set()) std::this_thread::yield();
  l << logger.str() << std::endl;
  lock_log.clear();
}


